package com.atdfrz.secondshop.controller.admin;

import com.atdfrz.secondshop.dto.LayuiResult;
import com.atdfrz.secondshop.mapper.CartMapper;
import com.atdfrz.secondshop.mapper.OrderDetailMapper;
import com.atdfrz.secondshop.mapper.OrderMapper;
import com.atdfrz.secondshop.mapper.ProductMapper;
import com.atdfrz.secondshop.pojo.Order;
import com.atdfrz.secondshop.pojo.User;
import com.atdfrz.secondshop.service.IAddressService;
import com.atdfrz.secondshop.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminOrderController {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ProductMapper productMapper;


    @RequestMapping("/orderlist")//跳转到订单页面首页
    public String toorderlist(){
        return "/admin/orders/order-list";
    }

    @RequestMapping("/catIndex")//跳转到小猫页面首页
    public String tocatIndex(){
        return "/admin/orders/index_v1";
    }

    @RequestMapping("/getAllOrderslist")
    @ResponseBody//查询所有订单列表
    public Map<String, Object> getAllOrderslist(Integer page, Integer limit) throws ParseException {
        PageHelper.startPage(page, limit);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Order::getCreateTime).orderByDesc(Order::getUpdateTime);
        List<Order> ordersList = orderMapper.selectList(wrapper);
        for(Order order:ordersList ){

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date=order.getCreateTime();
            String str = simpleDateFormat.format(date);
//            System.out.println(str);
            order.setCreateTimeStr(str);
        }
        PageInfo<Order> pageInfo = new PageInfo<>(ordersList);
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("data", pageInfo.getList());
        //count是total
        map.put("count", pageInfo.getTotal());
        return map;
    }

    @RequestMapping("/getOrderslistBycondition")
    @ResponseBody//根据订单的状态查询对应的订单列表
    public Map<String, Object> getOrderslistBycondition(Integer page, Integer limit,Integer status){
        PageHelper.startPage(page, limit);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(status!=null,Order::getStatus,status);
        wrapper.orderByDesc(Order::getCreateTime).orderByDesc(Order::getUpdateTime);
        List<Order> ordersList = orderMapper.selectList(wrapper);
        for(Order order:ordersList ){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date=order.getCreateTime();
            String str = simpleDateFormat.format(date);
//            System.out.println(str);
            order.setCreateTimeStr(str);
        }
        PageInfo<Order> pageInfo = new PageInfo<>(ordersList);
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("data", pageInfo.getList());
        //count是total
        map.put("count", pageInfo.getTotal());
        return map;
    }

    /**
     * 根据订单号模糊查询
     */
    @RequestMapping("/searchbyorder")
    @ResponseBody
    public Map<String, Object> searchbyorder(Long orderId, Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        PageInfo<Order> pageInfo=null;
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        if (orderId==null){
            //如果没有输入名字，则查询所有
            List<Order> ordersList = orderMapper.selectList(null);
            for(Order order:ordersList ){

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date=order.getCreateTime();
                String str = simpleDateFormat.format(date);
//            System.out.println(str);
                order.setCreateTimeStr(str);
            }
            pageInfo=new PageInfo<>(ordersList);
        }
        else {
            //否则则进行模糊查询
            wrapper.like(orderId!=null,Order::getOrderId,orderId);
            List<Order> ordersList = orderMapper.selectList(wrapper);
            for(Order order:ordersList ){

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date=order.getCreateTime();
                String str = simpleDateFormat.format(date);
//            System.out.println(str);
                order.setCreateTimeStr(str);
            }

            pageInfo=new PageInfo<>(ordersList);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("data", pageInfo.getList());
        //count是total
        map.put("count", pageInfo.getTotal());
        return map;
    }

    //0(用户取消订单);1(未付款);2(已付款，待发货);3(已发货);4(交易完成);
    @RequestMapping("/delever")
    @ResponseBody//管理员对待发货订单进行发货操作
    public LayuiResult delever(Long orderId){
        LayuiResult<Object> result = new LayuiResult<>();
        Order order = orderMapper.selectById(orderId);
        if (order==null){
            result.setCode(2);
            result.setMessage("订单信息异常，发货失败");
            return result;
        }
        //将订单状态设为发货
        order.setStatus(3);
        //保存进数据库
        int update = orderMapper.updateById(order);
        if (update>0){
            result.setCode(1);
            result.setMessage("发货成功");
            return result;
        }else {
            result.setCode(2);
            result.setMessage("发货失败");
            return result;
        }
    }

    //0(用户取消订单);1(未付款);2(已付款，待发货);3(已发货);4(交易完成);
    @PostMapping("/deleverMore")
    @ResponseBody//管理员对待发货订单进行批量发货操作
    public LayuiResult deleverMore(@RequestBody String[] orderIds){
        //将string类型的数组转化成long类型数组
        Long[] orders=new Long[orderIds.length];
        for (int i = 0; i < orderIds.length; i++) {
            orders[i]=Long.parseLong(orderIds[i]);
        }
        List<Long> odrerIdList = Arrays.asList(orders);
        //批量查询前端传来数据的订单id
        List<Order> orderList = orderMapper.selectBatchIds(odrerIdList);
        if (orderList!=null){
            for (Order order : orderList) {
                //将订单状态设为已发货
                order.setStatus(3);
                 orderMapper.updateById(order);
            }
        }
        LayuiResult<Object> result = new LayuiResult<>();
            result.setCode(1);
            result.setMessage("发货成功");
            return result;

//        orderService.updateBatchById()
    }

    @RequestMapping("/orderDetail")
    @ResponseBody//管理员查看订单的详情
    public LayuiResult orderDetail(Long orderId, HttpSession session,Model model){
        Order orderAndItem = orderMapper.findOrderAndItembyOrderId(orderId);
        LayuiResult<Order> result = new LayuiResult<>();
        if (orderAndItem!=null){
            model.addAttribute("orderAndItem",orderAndItem);
            session.setAttribute("orderAndItem",orderAndItem);
            result.setCode(1);
            result.setMessage("订单详情");
            result.setData(orderAndItem);
            return result;
        }
        result.setCode(2);
        result.setMessage("查看订单详情失败");
        return result;

    }





}
